<template>
  <div class="building-film-edit page-view">
    <!-- 面包屑导航 -->
    <div class="breadcrumb">
      <div class="list">
        <div class="home-icon">
          <i class="iconfont icon-home"></i>
        </div>
        <div class="item">
          <router-link to="/">
            <span class="text">首页</span>
          </router-link>
        </div>
        <div class="seperate">
          <i class="iconfont icon-arrow-right-thin"></i>
        </div>
        <div class="item">
          <router-link to="/buildingFilm">
            <span class="text">建筑家居膜管理</span>
          </router-link>
        </div>
        <div class="seperate">
          <i class="iconfont icon-arrow-right-thin"></i>
        </div>
        <div class="item">
          <span class="text">{{ isEdit ? '编辑建筑家居膜' : '添加建筑家居膜' }}</span>
        </div>
      </div>
      <h1 class="page-title">{{ isEdit ? '编辑建筑家居膜' : '添加建筑家居膜' }}</h1>
    </div>

    <!-- 表单内容 -->
    <div class="form-container">
      <form class="v-form" @submit.prevent="submitForm">
        <!-- 基本信息卡片 -->
        <div class="v-card">
          <div class="card-header">
            <h3>基本信息</h3>
          </div>
          <div class="card-body">
            <div class="form-grid">
              <!-- 产品分类 -->
              <div class="form-group">
                <label class="form-label">产品分类</label>
                <BaseSelect
                  v-model="formData.category_id"
                  :options="categoryOptions"
                  placeholder="请选择分类"
                  required
                />
              </div>

              <!-- 产品名称 -->
              <div class="form-group">
                <label class="form-label">产品名称</label>
                <input
                  v-model="formData.name"
                  type="text"
                  class="form-input"
                  placeholder="请输入产品名称"
                  required
                />
              </div>

              <!-- 可见光透射比 -->
              <div class="form-group">
                <label class="form-label">可见光透射比(%)</label>
                <input
                  v-model="formData.visible_light_transmittance"
                  type="number"
                  class="form-input"
                  placeholder="请输入可见光透射比"
                  min="0"
                  max="100"
                  step="0.01"
                  required
                />
              </div>

              <!-- 可见光反射比 -->
              <div class="form-group">
                <label class="form-label">可见光反射比(%)</label>
                <input
                  v-model="formData.visible_light_reflectance"
                  type="number"
                  class="form-input"
                  placeholder="请输入可见光反射比"
                  min="0"
                  max="100"
                  step="0.01"
                  required
                />
              </div>

              <!-- 太阳能总阻隔率 -->
              <div class="form-group">
                <label class="form-label">太阳能总阻隔率(%)</label>
                <input
                  v-model="formData.solar_energy_rejection"
                  type="number"
                  class="form-input"
                  placeholder="请输入太阳能总阻隔率"
                  min="0"
                  max="100"
                  step="0.01"
                  required
                />
              </div>

              <!-- 厚度 -->
              <div class="form-group">
                <label class="form-label">厚度(Mil)</label>
                <input
                  v-model="formData.thickness"
                  type="number"
                  class="form-input"
                  placeholder="请输入厚度"
                  min="0"
                  step="0.01"
                  required
                />
              </div>

              <!-- 紫外线阻隔率 -->
              <div class="form-group">
                <label class="form-label">紫外线阻隔率(%)</label>
                <input
                  v-model="formData.uv_rejection"
                  type="number"
                  class="form-input"
                  placeholder="请输入紫外线阻隔率"
                  min="0"
                  max="100"
                  step="0.01"
                  required
                />
              </div>

              <!-- 质保年限 -->
              <div class="form-group">
                <label class="form-label">质保年限</label>
                <input
                  v-model="formData.warranty"
                  type="text"
                  class="form-input"
                  placeholder="请输入质保年限"
                  required
                />
              </div>

              <!-- 产品图片 -->
              <div class="form-group full-width">
                <label class="form-label">产品图片</label>
                <ImgUploader
                  v-model="formData.image"
                  :max-size="5"
                  accept="image/*"
                />
                <div class="form-hint">建议尺寸：800x450，大小不超过5MB</div>
              </div>

              <!-- 产品描述 -->
              <div class="form-group full-width">
                <label class="form-label">产品描述</label>
                <textarea
                  v-model="formData.description"
                  class="form-input"
                  placeholder="请输入产品描述"
                  rows="4"
                ></textarea>
              </div>

              <!-- 创建时间 -->
              <div class="form-group" v-if="isEdit">
                <label class="form-label">创建时间</label>
                <input
                  type="text"
                  class="form-input"
                  :value="formatTimestamp(formData.created_at)"
                  disabled
                />
              </div>

              <!-- 更新时间 -->
              <div class="form-group" v-if="isEdit">
                <label class="form-label">更新时间</label>
                <input
                  type="text"
                  class="form-input"
                  :value="formatTimestamp(formData.updated_at)"
                  disabled
                />
              </div>
            </div>
          </div>
        </div>

        <!-- 表单操作按钮 -->
        <div class="form-actions">
          <button type="submit" class="v-button primary">提交保存</button>
          <button type="button" class="v-button" @click="goBack">返回</button>
        </div>
      </form>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { get, post } from "@/utils/request";
import { formatDate } from "@/utils/date";
import { vToast } from "@/plugins/vToast";
import BaseSelect from "@/components/BaseSelect.vue";
import ImgUploader from "@/components/ImageUploader.vue";

const route = useRoute();
const router = useRouter();

const isEdit = computed(() => route.name === 'BuildingFilmEdit');

// 分类选项
const categoryOptions = ref([]);

// 表单数据
const formData = ref({
  id: null,
  category_id: "",
  name: "",
  image: "",
  visible_light_transmittance: "",
  visible_light_reflectance: "",
  solar_energy_rejection: "",
  uv_rejection: "99.00",
  thickness: "",
  warranty: "",
  description: "",
  created_at: null,
  updated_at: null,
});

// 获取分类列表
const fetchCategories = async () => {
  try {
    const res = await get("/filmCategory/list", { type: 'building' });
    if (res.code === 200) {
      categoryOptions.value = res.data.map(item => ({
        value: item.id,
        text: item.name
      }));
    }
  } catch (error) {
    vToast.error("获取分类列表失败");
    console.error(error);
  }
};

// 格式化时间戳
const formatTimestamp = (timestamp) => {
  if (!timestamp) return "-";
  return formatDate(new Date(timestamp * 1000));
};

// 获取建筑家居膜详情
const fetchFilmDetail = async (id) => {
  try {
    const res = await get("/buildingFilm/detail", { id });
    if (res.code === 200 && res.data) {
      formData.value = {
        id: res.data.id,
        category_id: res.data.category_id || "",
        name: res.data.name || "",
        image: res.data.image || "",
        visible_light_transmittance: res.data.visible_light_transmittance || "",
        visible_light_reflectance: res.data.visible_light_reflectance || "",
        solar_energy_rejection: res.data.solar_energy_rejection || "",
        uv_rejection: res.data.uv_rejection || "99.00",
        thickness: res.data.thickness || "",
        warranty: res.data.warranty || "",
        description: res.data.description || "",
        created_at: res.data.created_at,
        updated_at: res.data.updated_at,
      };
    } else {
      vToast.error(res.msg || "获取建筑家居膜详情失败");
    }
  } catch (error) {
    vToast.error("获取建筑家居膜详情失败");
    console.error(error);
  }
};

// 提交表单
const submitForm = async () => {
  try {
    // 验证逻辑
    if (!formData.value.category_id) {
      vToast.warning("请选择产品分类");
      return;
    }
    
    if (!formData.value.name) {
      vToast.warning("请输入产品名称");
      return;
    }
    
    if (!formData.value.visible_light_transmittance) {
      vToast.warning("请输入可见光透射比");
      return;
    }
    
    if (!formData.value.solar_energy_rejection) {
      vToast.warning("请输入太阳能总阻隔率");
      return;
    }
    
    if (!formData.value.thickness) {
      vToast.warning("请输入厚度");
      return;
    }
    
    if (!formData.value.warranty) {
      vToast.warning("请输入质保年限");
      return;
    }

    // 准备提交数据
    const data = { ...formData.value };
    
    // 如果是新增模式，移除ID
    if (!isEdit.value) {
      delete data.id;
      delete data.created_at;
      delete data.updated_at;
    }

    const api = isEdit.value ? "/buildingFilm/update" : "/buildingFilm/add";
    const res = await post(api, data);

    if (res.code === 200) {
      vToast.success(isEdit.value ? "建筑家居膜更新成功" : "建筑家居膜添加成功");
      router.push("/buildingFilm");
    } else {
      vToast.error(res.msg || "操作失败");
    }
  } catch (error) {
    vToast.error("提交失败");
    console.error(error);
  }
};

// 返回
const goBack = () => {
  router.push("/buildingFilm");
};

// 初始化
onMounted(() => {
  fetchCategories();
  
  if (isEdit.value && route.params.id) {
    fetchFilmDetail(route.params.id);
  } else {
    // 设置默认值
    formData.value.uv_rejection = "99.00";
  }
});
</script>

<style scoped lang="less">
.building-film-edit {
  .breadcrumb {
    margin-bottom: 20px;
    
    .list {
      display: flex;
      align-items: center;
      font-size: 14px;
      
      .home-icon {
        color: #999;
      }
      
      .item {
        margin-right: 8px;
        
        .text {
          color: #333;
          
          &:hover {
            color: var(--v-theme);
          }
        }
      }
      
      .seperate {
        margin-right: 8px;
        color: #999;
      }
    }
    
    .page-title {
      margin-top: 10px;
      font-size: 24px;
      font-weight: 500;
      color: #333;
    }
  }

  .form-container {
    width: 100%;
    padding: 20px;
  }

  .v-card {
    border-radius: 4px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
    
    .card-header {
      padding: 16px 20px;
      border-bottom: 1px solid #eee;
      
      h3 {
        margin: 0;
        font-size: 16px;
        font-weight: 500;
        color: #333;
      }
    }
    
    .card-body {
      padding: 20px;
    }
  }

  .form-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 20px;
    
    .form-group {
      margin-bottom: 15px;
      
      &.full-width {
        grid-column: 1 / -1;
      }
      
      .form-label {
        display: block;
        margin-bottom: 8px;
        font-size: 14px;
        color: #333;
        font-weight: 500;
      }
      
      .form-input {
        width: 100%;
        padding: 10px 12px;
        border: 1px solid #ddd;
        border-radius: 4px;
        font-size: 14px;
        transition: border-color 0.3s;
        
        &:focus {
          border-color: var(--v-theme);
          outline: none;
        }
        
        &:disabled {
          background-color: #f5f5f5;
          cursor: not-allowed;
        }
      }
      
      textarea.form-input {
        min-height: 100px;
        resize: vertical;
      }
      
      .form-hint {
        margin-top: 8px;
        font-size: 12px;
        color: #999;
      }
    }
  }

  .form-actions {
    display: flex;
    justify-content: center;
    gap: 15px;
    margin-top: 30px;
    padding-top: 20px;
    border-top: 1px solid #eee;
    
    .v-button {
      min-width: 120px;
      height: 40px;
      padding: 0 20px;
      border-radius: 4px;
      font-size: 14px;
      cursor: pointer;
      
      &.primary {
        background-color: var(--v-theme);
        color: white;
        border: none;
        
        &:hover {
          background-color: var(--v-sidebar-background);
        }
      }
      
      &:not(.primary) {
        background-color: #fff;
        border: 1px solid #ddd;
        color: #333;
        
        &:hover {
          border-color: var(--v-theme);
          color: var(--v-theme);
        }
      }
    }
  }
}
</style>